/* DuplicateDataCheck.java
 * 6 Jun 2012
 */
package za.ac.wits.elen7045.integrity.checks;

import jass.modern.Post;
import jass.modern.Pre;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import za.ac.wits.elen7045.integrity.checks.interfaces.IntegrityCheck;
import za.ac.wits.elen7045.integrity.checks.interfaces.IntegrityCheckResult;
import za.ac.wits.elen7045.scraper.interfaces.ScrapeDataPairInterface;
import za.ac.wits.elen7045.scraper.interfaces.ScraperSessionInterface;

/**
 * Does a check on duplicate keys to see if the values correlate
 * 
 * @author Gerhard Visagie
 *
 */
public class DuplicateDataCheck implements IntegrityCheck {

	/* (non-Javadoc)
	 * @see za.ac.wits.elen7045.integrity.checks.interfaces.IntegrityCheck#doCheck(za.ac.wits.elen7045.scraper.interfaces.ScraperSessionInterface)
	 */
	@Override
	@Pre("scraperSession != null")
	@Post("@Result == true || @Result == false")
	public StandardIntegrityCheckReport doCheck(ScraperSessionInterface scraperSession) {
		//go through datapair, check if there is a correlating datapair in cache, compare values and if the same continue on
		//else just exit false
		HashMap<String, String> cacheMap = new HashMap<String, String>();
		
		List<IntegrityCheckResult> result = new ArrayList<IntegrityCheckResult>();
		boolean status = true;
		
		for(ScrapeDataPairInterface datapair:scraperSession.getDataPairs()){
			//does the key exist in the map, if not put it there
			if(cacheMap.get(datapair.getKey()) == null){
				cacheMap.put(datapair.getKey(), datapair.getValue());
			}else{
				//if it does exists, is it the same?
				if(!(datapair.getValue()).equals(cacheMap.get(datapair.getKey()))){
					//its not! return false
					status = false;
					result.add(new StandardIntegrityCheckResult(datapair.getKey(), datapair.getValue(), datapair.getKey(), cacheMap.get(datapair.getKey())));
				}
			}
		}
		
		//those keys we could find as duplicates where the same
		return new StandardIntegrityCheckReport(status, result);
	}

}
